package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.configuration.QueryPageParam;
import com.example.demo.dao.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.Response;
import com.example.demo.utils.Utils;
import com.example.demo.vo.UserVoEx;
import com.example.demo.vo.UserVoIn;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ArrayList<UserVoEx> selectAll() {
        List<User> users = userMapper.selectAll();
        ArrayList<UserVoEx> userVoExes = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            UserVoEx userVoEx = new UserVoEx();
            BeanUtils.copyProperties(users.get(i),userVoEx);
            userVoExes.add(userVoEx);
        }
        return userVoExes;
    }

    @Override
    public Response<Integer> save(UserVoIn userVoIn) {

        // 判断是否跳出跳出条件
        Response empty = UserServiceImpl.isEmpty(userVoIn);
        if (! empty.isSuccess()) {
            return empty;
        }

        // 转换为数据库需要的模式,增加数据，如果数据库报错返回报错数据
        User user = UserVoIn.exchange(userVoIn);
        int insert = 0;
        try {
            insert = userMapper.insert(user);
        }catch (DuplicateKeyException e){
            return Response.fail(300, "已有此账号！");
        }
        catch (Exception e) {
            return Response.fail(300,"数据库增加错误"+e.getMessage());
        }
        return Response.success(insert);
    }

    @Override
    public Response<Boolean> delete(int id) {
        int delete;
        // 删除用户，如果报错返回报错信息
        try {
            delete = userMapper.deleteById(id);
        } catch (Exception e) {
           return Response.fail(300, e.getMessage());
        }
        // 如果删除数量为0则没有这个用户未删除成功
        if (delete == 0){
            return Response.fail(300, "没有id为："+ id+"的这个用户");
        }
        return Response.success(true);
    }

    @Override
    public Response<Integer> deleteByAccount(String account) {
        // 判断账号是否为空0
        if (account == null && account.isEmpty()){
            return Response.fail(300,"账号不能为空");
        }

        // 设置删除条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account",account);

        // 定义接收参数
        int delete = 0;
        try {
            delete = userMapper.delete(wrapper);
        }catch (Exception e){
            return Response.fail(300,e.getMessage());
        }

        // 返回接受参数
        return Response.success(delete);
    }


    @Override
    public Response<UserVoEx> update(UserVoIn userVoIn) {
        // 如果账号为空
        Response empty = UserServiceImpl.isEmpty(userVoIn);
        if (! empty.isSuccess()) {
            return empty;
        }

        User user = UserVoIn.exchange(userVoIn);

        int update;
        try {
            UpdateWrapper<User> wrapper = getUserUpdateWrapper(user);
            update = userMapper.update(wrapper);
        } catch (Exception e) {
            return Response.fail(300, e.getMessage());
        }

        if (update == 0){
            return Response.fail(300, "修改失败");
        }

        // 修改成功返回数据
        UserVoEx userVoEx = UserVoEx.exchange(user);

        return Response.success(userVoEx);
    }

    /**
     *  更新条件生成
     * @param user 用户
     * @return  wrapper
     */
    private static UpdateWrapper<User> getUserUpdateWrapper(User user) {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("account", user.getAccount());

        // 如果 password 不为空
        if (user.getPassword()!= null &&!user.getPassword().isEmpty()) {
            wrapper.set("password1", user.getPassword());
        }

        wrapper.set("name", user.getName());
        wrapper.set("age", user.getAge());
        wrapper.set("sex", user.getSex());
        wrapper.set("phone", user.getPhone());
        wrapper.set("role_id", user.getRoleId());
        wrapper.set("isValid", user.getIsValid());
        return wrapper;
    }

    @Override
    public Response<List<UserVoEx>> listL(String name) {
        if(Utils.isEmpty(name)){
            return Response.fail(300, "模糊查询数据不能为空");
        }

        // 重新定义name为模糊查询模式
        name = "%" + name + "%";

        // 新建查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        System.out.println(name);
        queryWrapper.like("name",name);

        // 如果没错就查询
        List<User> users;
        try {
            users = userMapper.selectList(queryWrapper);
        } catch (Exception e) {
            return Response.fail(300, e.getMessage());
        }

        // 如果没有查到数据则直接返回
        if (users.isEmpty()){
            System.out.println("没有查询到数据");
            return Response.success(new ArrayList<UserVoEx>());
        }

        // 查出的数据转换为可输出类，放入新定义的数组中输出
        List<UserVoEx> userVoExs = new ArrayList<UserVoEx>();
        for (User user : users) {
            System.out.println(user);
            userVoExs.add(UserVoEx.exchange(user));
        }
        return Response.success(userVoExs);
    }

    @Override
    public Response<List<UserVoEx>> listPage(QueryPageParam param) {
        // 模糊查询重新定义name
        String name = "%" + param.getName() + "%";
        // 定义查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name);

        // 判读是否查询性别
        int sex = param.getSex();
        if (sex == 0 || sex == 1){
          queryWrapper.eq("sex",sex);
        }

        // 新建page查询
        Page<User> page = new Page<>(param.getPageNum(),param.getPageSize());

        // 定义查询接受变量
        ArrayList<UserVoEx> userVoExes = new ArrayList<>();

        // 如果报错则返回错误信息
        try{
            page = userMapper.selectPage(page,queryWrapper);
        }catch (Exception e){
            return Response.fail(300, e.getMessage());
        }

        // 获取总记录数
        long total = page.getTotal();

        // 获取数据
        List<User> users = page.getRecords();
        // 将数据转为可输出类
        for(User user: users){
            userVoExes.add(UserVoEx.exchange(user));
        }

        return Response.success(userVoExes,total);
    }

    @Override
    public Response<List<UserVoEx>> lists(QueryPageParam param) {
        // 新建page查询
        Page<User> page = new Page<>(param.getPageNum(), param.getPageSize());

        // 建立接受数组
        ArrayList<UserVoEx> userVoExes = new ArrayList<>();
        // 新建查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 新建查询
        try{
            page = userMapper.selectPage(page, wrapper);
        }catch (Exception e){
            return Response.fail(300, "查询错误");
        }

        // 接收
        List<User> users = page.getRecords();
        for (User user : users) {
            userVoExes.add(UserVoEx.exchange(user));
        }

        // 获取total总数
        long total = page.getTotal();
        return Response.success(userVoExes,total);
    }

    /**
     * 内部工具类 判断是否有为空不符合条件的内容
     * @param userVoIn 输入类数据
     * @return 成功或者失败
     */
    private static Response isEmpty(UserVoIn userVoIn){
        // 判断跳出条件
        if (Utils.isEmpty(userVoIn.getAccount())){
            return Response.fail(300,"账号不为空");
        }


        if (Utils.isEmpty(userVoIn.getName())){
            return Response.fail(300,"姓名不为空");
        }

        if (Utils.isEmpty(userVoIn.getIsValid())){
            return Response.fail(300,"是否有效不为空");
        }

        if (userVoIn.getAge() < 0 || userVoIn.getAge() > 200){
            return Response.fail(300,"年龄不符合条件");
        }
        return Response.success(null);
    }

}
